//
//  ILMusicRandomViewController.m
//  ILife
//
//  Created by lanou on 15/10/29.
//  Copyright © 2015年 ILife. All rights reserved.
//

#import "ILMusicRandomViewController.h"
#import "UIPopoverListView.h"
#import "ILMusicListModel.h"
#import "ILMusicListTableViewCell.h"
#import "ILMusicDetailViewController.h"

@interface ILMusicRandomViewController ()<UIPopoverListViewDataSource, UIPopoverListViewDelegate>
{
    NSInteger i;

}
@property(nonatomic, strong)ILMusicListModel *model;
@property(nonatomic,strong)UIPopoverListView *poplistview ;
@end

@implementation ILMusicRandomViewController
//- (void)viewDidAppear:(BOOL)animated
//{
//    [super viewDidAppear:animated];
//    [self becomeFirstResponder];
//}
//- (void) viewWillAppear:(BOOL)animated
//{
//    [self resignFirstResponder];
//    [super viewWillAppear:animated];
//}
//-(BOOL)canBecomeFirstResponder
//{
//    return YES;
//}
- (void) motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    
    if (motion == UIEventSubtypeMotionShake) {
        NSLog(@"摇一摇");
        i = arc4random()%(70 - 1);
        [self requestData];
        [UIView animateWithDuration:0.5 delay:0.5 usingSpringWithDamping:0.1 initialSpringVelocity:1.0 options:UIViewAnimationOptionTransitionFlipFromLeft animations:^{
            [self createbuildPoplistView];
        } completion:^(BOOL finished) {
            
        }];
       
    }
}

-(UIPopoverListView *)poplistview
{
    if (_poplistview == nil) {
        CGFloat xWidth = self.view.bounds.size.width - 20.0f;
        CGFloat yHeight = 272.0f;
        CGFloat yOffset = (self.view.bounds.size.height - yHeight)/2.0f;
        _poplistview= [[UIPopoverListView alloc] initWithFrame:CGRectMake(10, yOffset, xWidth, yHeight)];
    }
    return _poplistview;
}


-(void)createbuildPoplistView
{
    self.poplistview.delegate = self;
    self.poplistview.datasource = self;
    self.poplistview.listView.scrollEnabled = FALSE;
    
    [self.poplistview show];
}

-(void)requestData
{
    NSString *htmlStr =[NSString stringWithFormat:@"http://wawa.fm/CmsSite/a/cms/article/mylist?category.id=543&pageNo=%ld&pageSize=1&uid=0",(long)i];
    NSURL *url = [NSURL URLWithString:htmlStr];
    NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:url cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:10];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        
        NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        
        if (![str isEqualToString:@""]) {
            NSArray *arr = [str componentsSeparatedByString:@"("];
            NSString *dataStr = [[arr[1] componentsSeparatedByString:@")"] objectAtIndex:0];
            NSData *realData = [dataStr dataUsingEncoding:NSUTF8StringEncoding];
            NSArray *realArr = [NSJSONSerialization JSONObjectWithData:realData options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
            for (NSDictionary *dic in realArr) {
                _model = [[ILMusicListModel alloc]init];
                [_model setValuesForKeysWithDictionary:dic];
                
            }
            [self.poplistview setTitle:_model.articleData.singer];
            [_poplistview.listView reloadData];
        }
   
    }];
}
- (void)backList
{
    
    [self.navigationController popViewControllerAnimated:YES];
    
}
- (void)viewDidLoad {
    
    [super viewDidLoad];
    self.navigationItem.title = @"摇摇音乐人";
//     [[UINavigationBar appearance] setTintColor:[UIColor blackColor]];
    UIBarButtonItem *popItem = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"iconfont-listzhuanhuan"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(backList)];
    self.navigationItem.leftBarButtonItem = popItem;
    
    
    UIImageView *backGroundImage = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
    backGroundImage.center = self.view.center;
    backGroundImage.image = [UIImage imageNamed:@"yaoyiyao"];
    [self.view addSubview:backGroundImage];
    

    i = arc4random()%(70 - 1);
    [self requestData];
    [self createbuildPoplistView];
//    CGFloat xWidth = self.view.bounds.size.width - 20.0f;
//    CGFloat yHeight = 272.0f;
//    CGFloat yOffset = (self.view.bounds.size.height - yHeight)/2.0f;
//    _poplistview = [[UIPopoverListView alloc] initWithFrame:CGRectMake(10, yOffset, xWidth, yHeight)];
//    _poplistview.delegate = self;
//    _poplistview.datasource = self;
//    _poplistview.listView.scrollEnabled = FALSE;
//    [_poplistview setTitle:@"Share to"];
//    [_poplistview show];
    
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [UIView animateWithDuration:0.5 delay:0.5 usingSpringWithDamping:0.1 initialSpringVelocity:1.0 options:UIViewAnimationOptionTransitionFlipFromLeft animations:^{
      [self createbuildPoplistView];
    } completion:^(BOOL finished) {
        
    }];
   
}
#pragma mark - UIPopoverListViewDataSource

- (UITableViewCell *)popoverListView:(UIPopoverListView *)popoverListView
                    cellForIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"cell";
     ILMusicListTableViewCell *cell= [[ILMusicListTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                                    reuseIdentifier:identifier];
    
    cell.musicListModel = _model;
    return cell;
}

- (NSInteger)popoverListView:(UIPopoverListView *)popoverListView
       numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

#pragma mark - UIPopoverListViewDelegate
- (void)popoverListView:(UIPopoverListView *)popoverListView
     didSelectIndexPath:(NSIndexPath *)indexPath
{
    if (_model.musicId != nil && ![_model.musicId isEqualToString:@""] && ![_model.image isEqualToString:@""] && _model!= nil) {
        ILMusicDetailViewController *detailVC = [[ILMusicDetailViewController alloc]init];
        detailVC.musicID = _model.musicId;
        [self.navigationController pushViewController:detailVC animated:YES];
    }
}

- (CGFloat)popoverListView:(UIPopoverListView *)popoverListView
   heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 272.0f;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
